package cn.pinming.chyn.tools.utils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.simple.SimpleDataSource;
import cn.pinming.chyn.tools.exception.ChynException;

public class DbFactory {

	private Db db ;
	
	public DbFactory(String url , String user , String password) {
		DataSource ds = new SimpleDataSource(url, user, password);
        this.db = Db.use(ds);
	}
	
	public List<Entity> queryList(String sql , Map<String, Object> params){
		sqlNotEmpty(sql);
		try {
			return this.db.query(sql, params) ;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return new ArrayList<Entity>();
	}
	
	public void close() {
		try {
			db.getConnection().close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public List<Entity> queryList(String sql){
		return queryList(sql, null) ;
	}
	
	public Entity queryOne(String sql , Map<String, Object> params){
		sqlNotEmpty(sql);
		List<Entity> list = queryList(sql, params) ;
		return list.size() > 0 ? list.get(0) : null ;
	}
	
	public Entity queryOne(String sql){
		return queryOne(sql, null) ;
	}
	
	public int executeSql(String sql , Map<String, Object> params) {
		sqlNotEmpty(sql);
		try {
			return this.db.execute(sql, params) ;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0 ;
	}
	
	private void sqlNotEmpty(String sql) {
		if(StringUtils.isEmpty(sql)) {
			throw new ChynException("SQL为空") ;
		}
	}
	
}
